package com.shuaiche.yeguan.util;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import androidx.annotation.NonNull;

public class CrashHandler implements Thread.UncaughtExceptionHandler {
    private static final String TAG = "CrashHandler";
    private static CrashHandler instance;
    private Context context;
    private Thread.UncaughtExceptionHandler defaultHandler;

    private CrashHandler() {}

    public static CrashHandler getInstance() {
        if (instance == null) {
            synchronized (CrashHandler.class) {
                if (instance == null) {
                    instance = new CrashHandler();
                }
            }
        }
        return instance;
    }

    public void init(Context context) {
        this.context = context;
        Log.e(TAG, "CrashHandler init");
        defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {
        saveCrashInfoToFile(e);
        if (defaultHandler != null) {
            defaultHandler.uncaughtException(t, e);
        }
    }

    private void saveCrashInfoToFile(Throwable e) {
        String timeStamp = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
        String fileName = timeStamp + ".txt";

        File downloadDir = this.context.getExternalFilesDir("crash");
        Log.e(TAG,downloadDir.getAbsolutePath());

//        File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        File logFile = new File(downloadDir, fileName);

        try (FileWriter writer = new FileWriter(logFile)) {
            writer.write("Crash Time: " + timeStamp + "\n");
            writer.write("Exception: " + e.toString() + "\n");

            StackTraceElement[] stackTrace = e.getStackTrace();
            for (StackTraceElement element : stackTrace) {
                writer.write("\t" + element.toString() + "\n");
            }

            Log.d(TAG, "Crash log saved to: " + logFile.getAbsolutePath());
        } catch (IOException ex) {
            Log.e(TAG, "Failed to save crash log", ex);
        }
    }
}